package org.goldfish.demo.apicall.analysis.code.select;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.Label;
import javafx.stage.FileChooser;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.goldfish.demo.apicall.analysis.code.upload.messager.impl.pdf.PDFProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class PDFSelectorController {

    @FXML
    private Label selectedPathLabel;

    @FXML
    private Button selectFileButton;

    @FXML
    private Button selectFolderButton;

    @FXML
    private Button analyzeButton;

    @FXML
    private TextArea logArea;

    @Setter
    private Stage primaryStage;

    private File selectedFile;
    private File selectedFolder;
    private Thread processingThread;

    @Autowired
    private PDFProcessor pdfProcessor;

    @FXML
    private void initialize() {
        selectFileButton.setOnAction(e -> selectPDFFile());
        selectFolderButton.setOnAction(e -> selectPDFFolder());
        analyzeButton.setOnAction(e -> analyzeSelectedPDF());
        analyzeButton.setDisable(true);

        log("PDF分析工具已启动");
    }

    private void selectPDFFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("PDF Files", "*.pdf")
        );
        fileChooser.setTitle("选择PDF文件");

        File file = fileChooser.showOpenDialog(primaryStage);
        if (file != null) {
            selectedFile = file;
            selectedFolder = null;
            selectedPathLabel.setText(file.getAbsolutePath());
            analyzeButton.setDisable(false);
            log("已选择PDF文件: " + file.getName());
        }
    }

    private void selectPDFFolder() {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择包含PDF文件的文件夹");

        File folder = directoryChooser.showDialog(primaryStage);
        if (folder != null) {
            selectedFolder = folder;
            selectedFile = null;
            selectedPathLabel.setText(folder.getAbsolutePath());
            analyzeButton.setDisable(false);
            log("已选择文件夹: " + folder.getName());
        }
    }

    private void analyzeSelectedPDF() {
        // 如果已有线程在运行，先中断它
        if (processingThread != null && processingThread.isAlive()) {
            processingThread.interrupt();
        }

        processingThread = new Thread(() -> {
            try {
                if (selectedFile != null) {
                    log("开始处理PDF文件: " + selectedFile.getName());
                    List<File> imageFiles = pdfProcessor.processSinglePDF(selectedFile);
                    log("PDF文件处理完成，共生成 " + imageFiles.size() + " 张图片");
                    // 这里可以调用实际的分析逻辑
                } else if (selectedFolder != null) {
                    log("开始处理文件夹: " + selectedFolder.getName());
                    List<File> imageFiles = pdfProcessor.processPDFsInFolder(selectedFolder);
                    log("文件夹处理完成，共生成 " + imageFiles.size() + " 张图片");
                    // 这里可以调用实际的分析逻辑
                }
            } catch (IOException e) {
                log("处理PDF时出错: " + e.getMessage());
                log.error("处理PDF时出错", e);
            } catch (Exception e) {
                // 捕获线程中断等其他异常
                if (!(e instanceof InterruptedException)) {
                    log("处理PDF时发生未知错误: " + e.getMessage());
                    log.error("处理PDF时发生未知错误", e);
                }
            }
        });
        
        processingThread.setDaemon(false); // 设置为用户线程
        processingThread.start();
    }

    private void log(String message) {
        javafx.application.Platform.runLater(() -> 
            logArea.appendText("[" + java.time.LocalTime.now().toString().substring(0, 8) + "] " + message + "\n")
        );
        log.info(message);
    }
    
    /**
     * 在应用程序关闭前调用此方法来清理资源
     */
    public void cleanup() {
        if (processingThread != null && processingThread.isAlive()) {
            processingThread.interrupt();
            try {
                processingThread.join(1000); // 等待最多1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}